<template>
	<custom-navigation-bar class="nav-bar" title="核销记录" :back="true"></custom-navigation-bar>
	<scroll-view id="myScroll" class="vip-list" scroll-y style="flex: 1;overflow-y: hidden;" @scroll='scroll'
		:scroll-top="scrollTop" enhanced="true" lower-threshold="50" @scrolltolower="onScrollToLower"
		@scrolltoupper='scrolltoupper' :refresher-enabled="true" refresher-threshold="80"
		refresher-default-style="none" :refresher-triggered="triggered" :refresher-two-level-pinned="false"
		:refresher-two-level-scroll-enabled="false"
		:refresher-two-level-enabled='false' :refresher-two-level-threshold="150"
		:refresher-two-level-triggered="twoLevelTriggered" @refresherpulling="onPulling"
		@refresherrefresh="onRefresh" @refresherrestore="onRestore" @refresherabort="onAbort"
		@refresherstatuschange='onStatusChange'>
		<view slot="refresher" class="exp-room">
			<view class="expand" @tap="twoLevelTriggered=!twoLevelTriggered">
				<view class="refresher-tips">{{refreshStatus}}</view>
			</view>
		</view>
	<view class="verification-record">
		<!-- 顶部导航 -->

		<!-- 搜索和筛选区域 -->
		<view class="filter-bar flex-row">
			<view class="search-box">
				<image src="/static/icons/search.png" mode="widthFix" class="search-icon"></image>
				<input type="text" placeholder="搜索服务名称或用户" v-model="searchKeyword" @input="handleSearch"
					class="search-input" />
			</view>

			<view class="filter-btn" @click="showFilter = !showFilter">
				<image src="/static/icons/filter.png" mode="widthFix" class="filter-icon"></image>
				<text class="filter-text">筛选</text>
			</view>
		</view>

		<!-- 筛选面板 -->
		<view class="filter-panel" v-if="showFilter">
			<view class="filter-section">
				<view class="filter-title">服务类型</view>
				<view class="filter-options flex-row">
					<view class="filter-option" v-for="(item, index) in serviceTypes" :key="index"
						:class="{ 'active': selectedService === index }" @click="selectedService = index">
						{{ item }}
					</view>
				</view>
			</view>

			<view class="filter-section">
				<view class="filter-title">时间范围</view>
				<view class="date-picker flex-row">
					<picker mode="date" start="2023-01-01" end="2099-12-31" @change="onStartDateChange">
						<view class="picker-view">
							{{ startDate || '开始日期' }}
						</view>
					</picker>
					<view class="date-separator">至</view>
					<picker mode="date" start="2023-01-01" end="2099-12-31" @change="onEndDateChange">
						<view class="picker-view">
							{{ endDate || '结束日期' }}
						</view>
					</picker>
				</view>
			</view>

			<view class="filter-actions flex-row">
				<button class="reset-btn" @click="resetFilter">重置</button>
				<button class="confirm-btn" @click="confirmFilter">确认</button>
			</view>
		</view>

		<!-- 记录列表 -->
		<view class="record-list">
			<view class="record-item" v-for="(record, index) in filteredRecords" :key="index"
				@click="viewDetail(record)">
				<view class="record-header justify-between flex-row">
					<view class="service-name">{{ record.serviceName }}</view>
					<view class="record-status">{{ record.status }}</view>
				</view>

				<view class="record-body">
					<view class="record-info flex-row">
						<text class="info-label">用户：</text>
						<text class="info-value">{{ record.userName }}</text>
					</view>
					<view class="record-info flex-row">
						<text class="info-label">核销码：</text>
						<text class="info-value">{{ formatCode(record.code) }}</text>
					</view>
					<view class="record-info flex-row">
						<text class="info-label">核销时间：</text>
						<text class="info-value">{{ record.time }}</text>
					</view>
					<view class="record-info flex-row">
						<text class="info-label">核销员：</text>
						<text class="info-value">{{ record.verifier }}</text>
					</view>
				</view>

			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-if="filteredRecords.length === 0 && !loading">
				<text class="empty-text">暂无核销记录</text>
			</view>

			<!-- 加载中 -->
			<view class="loading-state" v-if="loading">
				<view class="loading-spinner"></view>
				<text class="loading-text">加载中...</text>
			</view>
		</view>

		<!-- 加载更多 -->
		<view class="load-more" v-if="hasMore && !loading" @click="loadMore">
			<text>加载更多</text>
		</view>
	</view>
	</scroll-view>
</template>

<script>
	export default {
		data() {
			return {
				refreshStatus: '下拉刷新',
				status: 0,
				// triggered
				twoLevelTriggered: false, //设置打开/关闭二级
				triggered: false, //true触发下拉刷新
				scrollTop: 0,
				// 搜索和筛选条件
				searchKeyword: '',
				showFilter: false,
				serviceTypes: ['全部', '国际贵宾通道', '国内贵宾通道', '易登机优享通道(2)', '易登机优享通道(3)', '易登机优享通道(4)'],
				selectedService: 0,
				startDate: '',
				endDate: '',

				// 数据相关
				records: [],
				filteredRecords: [],
				page: 1,
				pageSize: 10,
				hasMore: true,
				loading: false
			}
		},

		onLoad() {
			// 检查权限
			// this.checkPermission();
			// 加载数据
			this.loadRecords();
		},
		onReachBottom() {
			this.loadMore()
		},
		methods: {
			buildText(status) {
				switch (status) {
					case 0:
						return '下拉刷新'
					case 1:
						return '松手刷新，下拉进入二楼'
					case 2:
						return '正在刷新'
					case 3:
						return '刷新成功'
					case 4:
						return '刷新失败'
					case 5:
						return '松手进入二楼'
					default:
						return '进入二楼,点击返回'
				}
			},
			// onPulling自定义下拉刷新控件被下拉
			onStatusChange(e) {
				const status = e.detail.status
				console.log('status', status);
				this.status = status
				this.refreshStatus = this.buildText(status)
				if(status==7){
					wx.reLaunch({
					  url: '/pages/index/index',
					  routeType: 'wx://zoom'
					})
				}
			
			},
			onPulling(e) {
				// console.log('onPulling:', e)
			},
			
			onRefresh() {
				console.info('@@@ onRefresh')
				if (this._freshing) return
				this._freshing = true
				this.triggered = true
				console.log('_freshing', this);
				setTimeout(() => {
					this.triggered = false
					this._freshing = false
					console.log('_freshing', this);
				}, 2000)
			},
			
			onRestore(e) {
				console.log('onRestore:', e)
			},
			
			onAbort(e) {
				console.log('onAbort', e)
			},
			
			scroll(e) {
				// console.log('e',e);
			},
			onScrollToLower() {
				console.log('到底');
				if (this.loading) return
				this.loading = true;
							this.loadRecords()
			
			},
			scrolltoupper(e) {
				console.log('顶', 1);
			},
			// 返回上一页
			navBack() {
				uni.navigateBack();
			},

			// 检查权限
			checkPermission() {
				const userInfo = uni.getStorageSync('userInfo');
				if (!userInfo || userInfo.role !== 'staff') {
					uni.showToast({
						title: '没有查看权限',
						icon: 'none'
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 1000);
				}
			},

			// 加载核销记录
			loadRecords() {
				if (this.loading) return;

				this.loading = true;

				// 模拟API请求
				setTimeout(() => {
					// 生成模拟数据
					const mockData = [];
					for (let i = 0; i < this.pageSize; i++) {
						const id = (this.page - 1) * this.pageSize + i + 1;
						const serviceTypes = ['国际贵宾通道', '国内贵宾通道', '易登机优享通道(2)', '易登机优享通道(3)', '易登机优享通道(4)'];
						const randomType = Math.floor(Math.random() * 5);

						mockData.push({
							id,
							code: `VIP${Date.now() + id}`,
							serviceName: serviceTypes[randomType],
							userName: `用户${Math.floor(Math.random() * 1000)}`,
							time: this.formatTime(new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 *
								1000)),
							verifier: `核销员${Math.floor(Math.random() * 100)}`,
							status: '已核销',
							userType: ['散客', '固有会员', '散客储值'][Math.floor(Math.random() * 3)],
							cardType: ['限时不限次', '限次不限时'][Math.floor(Math.random() * 2)],
							price: Math.floor(Math.random() * 5) * 100 + 100
						});
					}

					if (this.page === 1) {
						this.records = mockData;
					} else {
						this.records = [...this.records, ...mockData];
					}

					// 应用筛选条件
					this.applyFilters();

					// 模拟数据到底
					if (this.page >= 3) {
						this.hasMore = false;
					}

					this.loading = false;
				}, 1000);
			},

			// 加载更多
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.page++;
					this.loadRecords();
				}
			},

			// 处理搜索
			handleSearch() {
				this.applyFilters();
			},

			// 开始日期选择
			onStartDateChange(e) {
				this.startDate = e.detail.value;
			},

			// 结束日期选择
			onEndDateChange(e) {
				this.endDate = e.detail.value;
			},

			// 重置筛选条件
			resetFilter() {
				this.selectedService = 0;
				this.startDate = '';
				this.endDate = '';
				this.searchKeyword = '';
				this.applyFilters();
			},

			// 确认筛选
			confirmFilter() {
				this.showFilter = false;
				this.applyFilters();
			},

			// 应用筛选条件
			applyFilters() {
				let result = [...this.records];

				// 服务类型筛选
				if (this.selectedService > 0) {
					const serviceName = this.serviceTypes[this.selectedService];
					result = result.filter(item => item.serviceName === serviceName);
				}

				// 搜索关键词筛选
				if (this.searchKeyword) {
					const keyword = this.searchKeyword.toLowerCase();
					result = result.filter(item =>
						item.serviceName.toLowerCase().includes(keyword) ||
						item.userName.toLowerCase().includes(keyword)
					);
				}

				// 日期范围筛选
				if (this.startDate) {
					result = result.filter(item => new Date(item.time) >= new Date(this.startDate));
				}

				if (this.endDate) {
					result = result.filter(item => new Date(item.time) <= new Date(this.endDate));
				}

				this.filteredRecords = result;
			},

			// 查看详情
			viewDetail(record) {
				uni.navigateTo({
					url: `/pages/verification/detail?info=${encodeURIComponent(JSON.stringify(record))}`
				});
			},

			// 格式化核销码（中间隐藏）
			formatCode(code) {
				if (code.length <= 8) return code;
				return code.substr(0, 4) + '****' + code.substr(-4);
			},

			// 格式化时间
			formatTime(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hour = date.getHours().toString().padStart(2, '0');
				const minute = date.getMinutes().toString().padStart(2, '0');
				return `${year}-${month}-${day} ${hour}:${minute}`;
			}
		}
	}
</script>

<style lang="scss">
	.verification-record {
		background-color: #f5f5f5;
		// min-height: 100vh;

		.nav-bar {
			display: flex;
			align-items: center;
			padding: 30rpx 20rpx;
			background-color: #fff;
			border-bottom: 1rpx solid #eee;

			.back-btn {
				width: 60rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				image {
					width: 30rpx;
					height: 30rpx;
				}
			}

			.title {
				flex: 1;
				text-align: center;
				font-size: 34rpx;
				font-weight: bold;
				color: #333;
			}
		}

		.filter-bar {
			display: flex;
			padding: 20rpx;
			background-color: #fff;
			border-bottom: 1rpx solid #eee;

			.search-box {
				flex: 1;
				display: flex;
				align-items: center;
				background-color: #f5f5f5;
				border-radius: 80rpx;
				padding: 0 30rpx;
				height: 70rpx;

				.search-icon {
					width: 30rpx;
					height: 30rpx;
					margin-right: 15rpx;
					opacity: 0.5;
				}

				.search-input {
					flex: 1;
					font-size: 26rpx;
					color: #333;
					height: 100%;
				}
			}

			.filter-btn {
				width: 120rpx;
				height: 70rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-left: 20rpx;

				.filter-icon {
					width: 30rpx;
					height: 30rpx;
					margin-right: 5rpx;
				}

				.filter-text {
					font-size: 26rpx;
					color: #333;
				}
			}
		}

		.filter-panel {
			background-color: #fff;
			border-bottom: 1rpx solid #eee;
			padding: 20rpx;

			.filter-section {
				margin-bottom: 30rpx;

				&:last-child {
					margin-bottom: 20rpx;
				}

				.filter-title {
					font-size: 28rpx;
					font-weight: 500;
					color: #333;
					margin-bottom: 15rpx;
				}

				.filter-options {
					display: flex;
					flex-wrap: wrap;
					gap: 15rpx;

					.filter-option {
						padding: 10rpx 20rpx;
						background-color: #f5f5f5;
						border-radius: 60rpx;
						font-size: 24rpx;
						color: #666;

						&.active {
							background-color: #e8f0fe;
							color: #1a73e8;
						}
					}
				}

				.date-picker {
					display: flex;
					align-items: center;
					gap: 20rpx;

					.picker-view {
						flex: 1;
						height: 70rpx;
						line-height: 70rpx;
						background-color: #f5f5f5;
						border-radius: 8rpx;
						padding: 0 20rpx;
						font-size: 26rpx;
						color: #333;
					}

					.date-separator {
						font-size: 28rpx;
						color: #999;
					}
				}
			}

			.filter-actions {
				display: flex;
				gap: 20rpx;
				margin-top: 20rpx;

				.reset-btn {
					flex: 1;
					height: 80rpx;
					line-height: 80rpx;
					background-color: #f5f5f5;
					color: #666;
					font-size: 28rpx;
					border-radius: 8rpx;
				}

				.confirm-btn {
					flex: 1;
					height: 80rpx;
					line-height: 80rpx;
					background-color: #1a73e8;
					color: #fff;
					font-size: 28rpx;
					border-radius: 8rpx;
				}
			}
		}

		.record-list {
			padding: 20rpx;

			.record-item {
				background-color: #fff;
				border-radius: 16rpx;
				padding: 25rpx;
				margin-bottom: 20rpx;
				box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
				position: relative;

				&:last-child {
					margin-bottom: 0;
				}

				.record-header {
					display: flex;
					justify-content: space-between;
					margin-bottom: 20rpx;

					.service-name {
						font-size: 28rpx;
						font-weight: 500;
						color: #333;
					}

					.record-status {
						width: max-content;
						font-size: 24rpx;
						color: #07c160;
						background-color: #f6ffed;
						padding: 5rpx 15rpx;
						border-radius: 60rpx;
					}
				}

				.record-body {
					.record-info {
						display: flex;
						margin-bottom: 15rpx;

						&:last-child {
							margin-bottom: 0;
						}

						.info-label {
							font-size: 24rpx;
							color: #999;
							width: 120rpx;
						}

						.info-value {
							font-size: 24rpx;
							color: #666;
							flex: 1;
						}
					}
				}

				.record-footer {
					position: absolute;
					right: 25rpx;
					top: 50%;
					transform: translateY(-50%);

					.arrow-icon {
						width: 24rpx;
						height: 24rpx;
						opacity: 0.5;
					}
				}
			}

			.empty-state {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 100rpx 0;

				.empty-icon {
					width: 150rpx;
					height: 150rpx;
					opacity: 0.3;
					margin-bottom: 30rpx;
				}

				.empty-text {
					font-size: 28rpx;
					color: #999;
				}
			}

			.loading-state {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 100rpx 0;

				.loading-spinner {
					width: 50rpx;
					height: 50rpx;
					border: 5rpx solid rgba(26, 115, 232, 0.1);
					border-radius: 50%;
					border-top-color: #1a73e8;
					animation: spin 1s ease-in-out infinite;
					margin-bottom: 30rpx;
				}

				.loading-text {
					font-size: 28rpx;
					color: #999;
				}
			}
		}

		.load-more {
			padding: 30rpx 0;
			text-align: center;
			font-size: 26rpx;
			color: #1a73e8;
			background-color: #fff;
			margin: 20rpx;
			border-radius: 16rpx;
		}
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}
</style>